#include "musiclist.h"

#include <QMimeDatabase>
#include <QDebug>
#include <music.h>

MusicList::MusicList()
{

}

void MusicList::addMusicByUrls(QList<QUrl> musicUrls)
{
    for(auto& e : musicUrls)
    {
        QString musicPath = e.toLocalFile();
        if(musicPaths.contains(musicPath))
            continue;

        musicPaths << musicPath;

        //过滤有效歌曲文件
        QMimeDatabase mimeDataBase;
        QMimeType mimeType = mimeDataBase.mimeTypeForFile(e.toLocalFile());
        QString mimeKind = mimeType.name();
        if(mimeKind == "audio/mpeg" || mimeKind == "audio/flac" || mimeKind == "audio/wav")
        {
            //需要将 url 创建一个 music 对象，然后添加到 musicList 中
            Music music(e);
            musicList.push_back(music);
        }
    }
}

//根据 musicId 查找对应歌曲
MusicList::iterator MusicList::findMusicByMusicId(const QString &musicId)
{
    auto it = musicList.begin();
    while(it != musicList.end())
    {
        if(it->getMusicId() == musicId)
            return it;
        it++;
    }
    return musicList.end();
}

void MusicList::writeToDB()
{
    for(auto& music : musicList)
    {
        music.insertToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, musicAlbum,\
                        musicUrl, duration, isLike, isHistory FROM musicInfo");
    QSqlQuery query;

    if(!query.exec(sql))
    {
        qDebug() << "查询失败：" << query.lastError().text();
        return;
    }

    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbum(query.value(3).toString());
        music.setMusicUrl("file:///" + query.value(4).toString());
        music.setDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        musicList << music;

        //musicPaths.insert(music.getMusicUrl().toLocalFile());
        musicPaths << music.getMusicUrl().toLocalFile();
    }
}
